package com.hudson.namesrv;


import com.hudson.codec.MessageCodecFactory;
import com.hudson.core.util.PropertiesUtil;
import com.hudson.namesrv.config.NameSrvConfig;
import com.hudson.namesrv.handler.BrokerMessageHandler;
import com.hudson.namesrv.handler.IdleMessageHandler;
import com.hudson.namesrv.handler.ProducerMessageHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 渔小鲤
 * @DateTime: 2025/7/12 19:58
 **/
public class NameSrv {
    private static final Logger logger = LoggerFactory.getLogger(NameSrv.class);


    public static void main(String[] args) {
        // 加载配置文件
        Properties prop = PropertiesUtil.getProperties("NameSrvConfig.properties");

        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(new NioEventLoopGroup(NameSrvConfig.bossThreads), new NioEventLoopGroup(NameSrvConfig.workerThreads))
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel sc) throws Exception {
                        sc.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 8, 4, 0, 0));
                        sc.pipeline().addLast(MessageCodecFactory.getCodec(NameSrvConfig.serializableMethod));
                        sc.pipeline().addLast(new BrokerMessageHandler());
                        sc.pipeline().addLast(new IdleStateHandler(30, 0, 0, TimeUnit.MINUTES));
                        sc.pipeline().addLast(new IdleMessageHandler());
                        sc.pipeline().addLast(new ProducerMessageHandler());
                    }
                });
        try {
            Channel channel = serverBootstrap.bind(new InetSocketAddress(NameSrvConfig.address, NameSrvConfig.port))
                    .sync()
                    .channel();


            logger.debug("NameSrv 已启动，监听端口: {}", NameSrvConfig.port);
            logger.info("NameSrv地址: {}", NameSrvConfig.address + ":" + NameSrvConfig.port);
        } catch (InterruptedException e) {
            logger.error("NameSrv 绑定端口失败");
        }

    }
}